package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.service.BusinessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/businesses")
@Tag(name = "管理店铺", description = "提供对店铺的增删改查功能")
public class BusinessController {

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessService businessService;

    @GetMapping("")
    @Operation(summary = "查询所有店铺", description = "获取系统中的所有店铺列表")
    public HttpResult<List<Business>> getBusinesses() {
        try {
            return businessService.getAllBusinesses();
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取店铺列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/search")
    @Operation(summary = "按名称关键词搜索店铺", description = "根据关键词搜索店铺，关键词为空时返回所有店铺")
    public HttpResult<List<Business>> searchBusinesses(
            @Parameter(description = "搜索关键词，为空时返回所有店铺") 
            @RequestParam(required = false) String keyword) {
        
        try {
            // 处理空关键词情况
            if (keyword == null || keyword.trim().isEmpty()) {
                return businessService.getAllBusinesses();
            }
            
            return businessService.searchByBusinessName(keyword.trim());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "搜索店铺失败: " + e.getMessage());
        }
    }

    @PostMapping("")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "添加新店铺（仅管理员）", description = "创建新的店铺，需要管理员权限")
    public HttpResult<Business> addBusiness(@RequestBody Business business) {
        try {
            return businessService.addBusiness(business);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "添加店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询店铺", description = "根据店铺ID获取店铺详细信息")
    public HttpResult<Business> getBusiness(
            @Parameter(description = "店铺ID", required = true) @PathVariable("id") Long id) {
        try {
            return businessService.getBusinessById(id);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "获取店铺详情失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "全量更新店铺信息（仅管理员）", description = "更新指定ID的店铺所有信息，需要管理员权限")
    public HttpResult<Business> updateBusiness(
            @Parameter(description = "店铺ID", required = true) @PathVariable("id") Long id, 
            @RequestBody Business business) {
        try {
            return businessService.updateBusiness(id, business);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "更新店铺失败: " + e.getMessage());
        }
    }

    @PatchMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "部分更新店铺信息（仅管理员）", description = "更新指定ID的店铺部分信息，仅管理员可操作")
    public HttpResult<Business> patchBusiness(
            @Parameter(description = "店铺ID", required = true) @PathVariable("id") Long id, 
            @RequestBody Business business) {
        try {
            // 复用update方法实现部分更新
            return businessService.updateBusiness(id, business);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "更新店铺失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "删除店铺（仅管理员）", description = "删除指定ID的店铺，需要管理员权限")
    public HttpResult<Void> deleteBusiness(
            @Parameter(description = "店铺ID", required = true) @PathVariable("id") Long id) {
        try {
            return businessService.deleteBusiness(id);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, 
                    "删除店铺失败: " + e.getMessage());
        }
    }
}